package com.kexun.config.shiro;

import com.kexun.entity.DO.Manage;
import com.kexun.entity.DO.Permission;
import com.kexun.entity.DO.Role;
import com.kexun.service.ManageService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class UserRealm extends AuthorizingRealm {

    @Autowired
    ManageService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {

        //获取用户的输入的账号.
        String username = (String) token.getPrincipal();
        Manage user = userService.findByUserName(username);
        if (user == null) {
            return null;
        }
        if (user.getIsLock() == 1) {
            throw new DisabledAccountException("此用户已被禁用");
        }
        Integer uid = user.getId();
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                uid,
                user.getPassword(),
                ByteSource.Util.bytes(user.getManageName() + user.getSalt()),
                getName()
        );
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        int userId = (int) principals.getPrimaryPrincipal();
        Manage user = userService.findUserById(userId);
        Role role = user.getRole();
        if (role != null) {
            authorizationInfo.addRole(role.getRoleName());
            for (Permission p : role.getPermissionList()) {
                //设置权限
                authorizationInfo.addStringPermission(p.getPermissionName());
            }
        }
        return authorizationInfo;
    }

}
